<?php

namespace cf;

require_once dirname(__FILE__).'/config.php';
require_once Config::path.'db_pdo.php';


$db = new Database('mysql:host='.Config::host.';dbname='.Config::db, Config::user, Config::pass, 'utf8');


define('INVALID_ID',0);

/*
	%d Day of the month, numeric (00..31) 
	%e Day of the month, numeric (0..31) 
	%m Month, numeric (00..12)
	%Y Year, numeric, four digits 
	
	%H Hour (00..23) 
	%h Hour (01..12) 
	%i Minutes, numeric (00..59) 
	%s Seconds (00..59) 
*/


function dbDateFormat($fnm, $fmt) { 			//oracle: TO_CHAR(fnm, 'DD-MON-YYYY HH:MI:SS')
	return "DATE_FORMAT($fnm,'$fmt')";
}

function dbDateCurrent() {							//oracle: SYSDATE
	return 'CURRENT_TIMESTAMP';
}

function dbDummyTable() {
	return 'DUAL';
}

function createQuery($sql, $params=array())
{
	global $db;
	$q = new Query($db);
	$q->prepare($sql);

	foreach ($params as $n => $v) {
		$q->setParam($n, $v);
	}
	
	return $q;
}

function createStaticQuery(&$q, $sql, $params=array())
{
   if (is_null($q)) {
      $q = createQuery($sql,$params);
   }
}


function execQuery($sql, $params=array(), &$processedCount=0)
{
	global $db;
	
	if (empty($params)) 
	{
		$q = new Query($db);
		$q->exec($sql);
		return $q->processedCount();
	}
	$q = createQuery($sql, $params);
	$q->execute();
	$processedCount = $q->processedCount();
	return $db->lastInsertId();
}

/** obsolete, use DB::countRecords */
function countRecords($tnm, $where=array()) 
{
	global $db;
	$q = new Select($db, $tnm);
	$q->addFields('COUNT(*)');
	$q->addWhereArray($where);
	$q->run();
	$q->fetch();
	$count = $q->at(0);
	$q->close();
	return $count;
}



//works for MYSQL only
function limitSelect($sql, $limit, $skip=0)
{
	if ($skip || $limit) {
		return $sql.' LIMIT '.($skip?"$skip,":'').($limit?$limit:'18446744073709551615');
	}
	return $sql;
}


/**
	all records
	@param $query   SQL query or iQuery ancestor object prepared and executed
*/
function query2arrays($query, $params=array(), $noNames=false, $keyName='')
{
	$records = array();
	$q = null;
	
	if (is_string($query))
	{
		$q = createQuery($query, $params);
		$q->execute();
	}
	else
	{
		$q = $query;
		foreach ($params as $nm => $val) {
			$q->setParam($nm,$val);
		}
		$q->execute();
	}
	
	while ($q->fetch($noNames?DB_FETCH_NUM:DB_FETCH_ASSOC))
	{
		$fields = array();
		foreach ($q as $fname => $fval)
		{
			$fields[$fname] = $fval;
		}
		if ($keyName) {
			$records[$q->at($keyName)] = $fields;
		}
		else {
			$records[] = $fields;
		}
	}
	$q->close();
	
	return $records;
}

/**
	one (first) record
	@param $query   SQL query or iQuery ancestor object prepared and executed
*/
function query2array($query, $params=array())
{
	$fields = array();
	$q = null;
	
	if (is_string($query))
	{
		$q = createQuery($query, $params);
		$q->execute();
	}
	else
	{
		$q = $query;
		foreach ($params as $nm => $val) {
			$q->setParam($nm,$val);
		}
		$q->execute();
	}
	
	if ($q->fetch(DB_FETCH_ASSOC))
	{
		foreach ($q as $fname => $fval)
		{
			$fields[$fname] = $fval;
		}
	}
	$q->close();
	
	return $fields;
}

/**
	put first field of every record to array
	@param $query   SQL query or iQuery ancestor object prepared and executed
*/
function query2vector($query, $params=array())
{
	$vector = array();
	$q = null;
	
	if (is_string($query))
	{
		$q = createQuery($query, $params);
		$q->execute();
	}
	else
	{
		$q = $query;
	}
	
	while ($q->fetch(DB_FETCH_NUM))
	{
		$vector[] = $q->at(0);
	}
	$q->close();
	
	return $vector;
}


function query2var($query, $params=array())
{
	$val = false;
	
	$q = null;
	if (is_string($query)) {
		$q = createQuery($query, $params);
	} else {
		$q = $query;
		$q->setParams($params);
	}		
	if ($q->execute()->fetch(DB_FETCH_NUM)) {
		$val = $q->at(0);
	}
	$q->close();
	return $val;
}


class DB
{
   static public function countRecords($sql, $params=array())
   {
	  $sql = preg_replace('/[\n\r]/','',$sql);
	  $sql = preg_replace('/LIMIT [0-9,]*/i', '', $sql);
      $sql = preg_replace('/[ ]*ORDER BY .+$/i','', $sql);
	  
      return query2var("SELECT COUNT(*) FROM ($sql) AS t", $params);
   }
};


?>